﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
namespace NetCoreCMS.Web.Areas.Admin.Controllers
{
    public class Manager_EditController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Manager/Manager_Edit.cshtml";
        string defaultpassword = "0|0|0|0"; //默认显示密码
        private string action = CMSEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
            if (context.Result != null)
                return;
            ChkAdminLevel("manager_list", CMSEnums.ActionEnum.View.ToString()); //检查权限
            ActionResult result = View(EDIT_RESULT_VIEW);
            string action = Request.Query["action"].FirstOrDefault();
            if (!string.IsNullOrEmpty(action) && action == CMSEnums.ActionEnum.Edit.ToString())
            {
                this.action = CMSEnums.ActionEnum.Edit.ToString();//修改类型
                if (!int.TryParse(Request.Query["id"].FirstOrDefault(), out this.id))
                {
                    ViewBag.ClientScript = JscriptMsg("传输参数不正确！", "back");
                    context.Result = result;
                    return;
                }
                if (!_manager.Exists(this.id))
                {
                    ViewBag.ClientScript = JscriptMsg("记录不存在或已被删除！", "back");
                    context.Result = result;
                    return;
                }
            }
            ViewBag.Action = action;
            ViewBag.DefaultPassword = defaultpassword;
            ViewBag.Id = this.id.ToString();
        }
        //
        // GET: /admin/Manager_Edit/

        public ActionResult Index()
        {
            var model = GetAdminInfo(); //取得管理员信息
            RoleBind(model.role_type);
            if (action == CMSEnums.ActionEnum.Edit.ToString())
            {
                ShowInfo(this.id);
            }
            else
            {
                ViewData["model"] = new Manager();
            }
            return View(WEB_VIEW);
        }

        [HttpPost]
        public ActionResult SubmitSave()
        {
            ActionResult result = View(EDIT_RESULT_VIEW);
            if (action == CMSEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("manager_list", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    ViewBag.ClientScript = JscriptMsg("保存过程中发生错误！", "back");
                    return result;
                }
                ViewBag.ClientScript = JscriptMsg("修改管理员信息成功！", "../manager_list/index");
            }
            else //添加
            {
                ChkAdminLevel("manager_list", CMSEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    ViewBag.ClientScript = JscriptMsg("保存过程中发生错误！", "back");
                    return result;
                }
                ViewBag.ClientScript = JscriptMsg("添加管理员信息成功！", "../manager_list/index");
            }
            return result;
        }

        #region 角色类型=================================
        private void RoleBind(int role_type)
        {
            var roles = _manager_role.GetList();
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem() { Text = "请选择角色...", Value = "" });
            foreach (var dr in roles)
            {
                if (dr.role_type >= role_type)
                {
                    list.Add(new SelectListItem() { Text = dr.role_name, Value = dr.id.ToString() });
                }
            }
            ViewData["list"] = list;
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            var model = _manager.GetModel(_id);
            ViewData["model"] = model;
            ViewBag.ClientScript = "$('#txtUserName').removeAttr('ajaxurl').attr('disabled','disabled');";
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            Manager model = new Manager();
            model.role_id = int.Parse(Request.Form["ddlRoleId"]);
            model.role_type = _manager_role.GetModel(model.role_id).role_type;
            if ((Request.Form["cbIsLock"]).ToString().ToLower().IndexOf("true") >= 0)
            {
                model.is_lock = 0;
            }
            else
            {
                model.is_lock = 1;
            }
            //检测用户名是否重复
            if (_manager.Exists(Request.Form["txtUserName"].ToString().Trim()))
            {
                return false;
            }
            model.user_name = Request.Form["txtUserName"].ToString().Trim();
            //获得6位的salt加密字符串
            model.salt = Utils.GetCheckCode(6);
            //以随机生成的6位字符串做为密钥加密
            model.password = AESEncryptHelper.Encode(Request.Form["txtPassword"].ToString().Trim(), model.salt);
            model.real_name = Request.Form["txtRealName"].ToString().Trim();
            model.telephone = Request.Form["txtTelephone"].ToString().Trim();
            model.email = Request.Form["txtEmail"].ToString().Trim();
            model.add_time = DateTime.Now;

            if (_manager.Add(model) > 0)
            {
                AddAdminLog(CMSEnums.ActionEnum.Add.ToString(), "添加管理员:" + model.user_name); //记录日志
                return true;
            }
            return false;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            bool result = false;
            var model = _manager.GetModel(_id);

            model.role_id = int.Parse(Request.Form["ddlRoleId"]);
            model.role_type = _manager_role.GetModel(model.role_id).role_type;
            if (Request.Form["cbIsLock"].ToString().ToLower().IndexOf("true") >= 0)
            {
                model.is_lock = 0;
            }
            else
            {
                model.is_lock = 1;
            }
            //判断密码是否更改
            if (Request.Form["txtPassword"].ToString().Trim() != defaultpassword)
            {
                //获取用户已生成的salt作为密钥加密
                model.password = AESEncryptHelper.Encode(Request.Form["txtPassword"].ToString().Trim(), model.salt);
            }
            model.real_name = Request.Form["txtRealName"].ToString().Trim();
            model.telephone = Request.Form["txtTelephone"].ToString().Trim();
            model.email = Request.Form["txtEmail"].ToString().Trim();

            if (_manager.Update(model))
            {
                AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "修改管理员:" + model.user_name); //记录日志
                result = true;
            }

            return result;
        }
        #endregion
    }
}
